<template>
  <a-spin :spinning="spinning">
    <div style="overflow: auto">
      <div
        class="svg-contain"
        v-if="infoWaterTemplateVo.waterTemplateInfo.length"
      >
        <svg
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          xmlns:xlink="http://www.w3.org/1999/xlink"
          :style="{
            'background-image':
              infoWaterTemplateVo.bgImg.type != 'default'
                ? `url(${infoWaterTemplateVo.bgImg.base64Data})`
                : '',
            backgroundColor:
              infoWaterTemplateVo.bgImg.type == 'default' ? '#000000' : '',
          }"
          class="svgContent"
          @dblclick="clearSelectSvgInfo"
          ref="svgModal"
        >
          <defs />
          <g
            v-for="(item, index) in infoWaterTemplateVo.waterTemplateInfo"
            :key="item"
            :id="item.componentDataId"
            :title="item.title"
            :transform="
              'translate(' +
              item.svgPositionX +
              ',' +
              item.svgPositionY +
              ')' +
              'rotate(' +
              item.angle +
              ')' +
              'scale(' +
              item.size +
              ')'
            "
            :class="[
              selectSvgInfo.componentDataId == item.componentDataId
                ? 'topo-layer-view-selected'
                : '',
              'cursor',
            ]"
            @mouseover="mouseoverSvg($event, index)"
            @mouseleave="clearSelectSvgInfo"
          >
            <SvgComponents
              :component_prop="item"
              :svgInfoData="infoWaterTemplateVo.waterTemplateInfo"
            ></SvgComponents>
          </g>
        </svg>
      </div>
      <a-empty style="margin-top: 30%" e-else description="暂无相关数据" />
      <div v-if="isShowBackButton == '1'" class="btns-content">
        <a-button type="primary" @click="returnRouter">返回</a-button>
      </div>
      <!--详情框-->
      <div
        ref="componentInfoModal"
        v-show="showComponentInfoModal"
        class="componentInfoModal"
      >
        <div class="title">{{ selectSvgInfo.title }}</div>
        <template v-if="selectSvgInfo.type == 'WaterPipeValveSvg'">
          <div v-if="selectSvgInfo.stateKeyValue != null">
            设备状态:{{ valve_status[selectSvgInfo.stateKeyValue] }}
          </div>
          <div v-if="selectSvgInfo.dataKeyValue != null">
            阀门状态:{{ valve_data[selectSvgInfo.dataKeyValue] }}
          </div>
        </template>
        <div v-else>
          {{ selectSvgInfo.stateKeyValue || selectSvgInfo.dataKeyValue }}
        </div>
      </div>
      <!--地址选择框-->
      <div v-if="isShowSelect == '1'" class="selectAddress">
        <a-select
          v-model:value="selectAddress"
          style="min-width: 120px"
          :dropdownMatchSelectWidth="250"
          @change="changeSelect"
          option-label-prop="children"
          placeholder="请选择地址"
        >
          <a-select-option
            v-for="item in addressSelecter"
            :key="item"
            :value="item.deviceAreaId"
            :label="item.equipmentName"
            >{{ item.equipmentName }}</a-select-option
          >
        </a-select>
      </div>
      <div class="screen" v-if="infoWaterTemplateVo.waterTemplateInfo.length">
        <div v-if="isScreenFull">
          <fullscreen-exit-outlined @click="isScreenFullEvent(false)" />
        </div>
        <div v-else>
          <fullscreen-outlined @click="isScreenFullEvent(true)" />
        </div>
      </div></div
  ></a-spin>
</template>
<script>
import { Storage } from '@/util/storage.js';
import {
  FullscreenExitOutlined,
  FullscreenOutlined,
} from '@ant-design/icons-vue';
import '@/assets/css/svgAnimation/index.css';
import SvgComponents from '@/components/SvgComponents.vue';
import {
  listComponent,
  infoTemplate,
  getMachineRoomList,
  machineRoomTemplateRendering,
} from '@/network/api/index';
import { message } from 'ant-design-vue';
export default {
  components: { SvgComponents, FullscreenExitOutlined, FullscreenOutlined },
  data() {
    return {
      isScreenFull: Storage.get('isScreenFull') || false,
      spinning: false,
      selectAddress: null,
      selectSvgInfo: {},
      infoWaterTemplateVo: {
        bgImg: {},
        addEventGroupDetailForm: [], //分组模板数据
        waterTemplateInfo: [], //普通模板数据
        keyValue: [],
      },
      isShowSelect: '1',
      isShowBackButton: '0',
      showComponentInfoModal: false,
      addressSelecter: [],
      valve_data: {
        0: '关',
        1: '开',
      },
      valve_status: {
        0: '故障',
        1: '正常',
      },
      //阀门状态
      valveStatus: {
        0: 'closeValve',
        1: 'openValve',
      },
      //阀门开关
      switchStatus: {
        0: 'closeValve',
        1: 'openValve',
      },
    };
  },
  mounted() {
    // let _this = this;
    //请求接口获取组件
    this.$nextTick(() => {
      this.spinning = true;
      this.isShowBackButton = this.$route.params.isShowBackButton || '0';
      this.isShowSelect = this.$route.params.isShowSelect || '1';
      //获取地址
      this.$httpRequest(getMachineRoomList, {
        pageSize: -1,
        currPage: -1,
      })
        .then((res) => {
          if (res.records) {
            this.addressSelecter = res.records;
            this.previewModel(
              this.$route.params.waterTemplateId || res.records[0].deviceAreaId
            );
          }
        })
        .catch(() => {
          this.spinning = false;
        });
      if (Storage.get('selectAreaId')) {
        this.selectAddress = Storage.get('selectAreaId');
        this.getTemplateList(Storage.get('selectAreaId'));
      }
    });
  },
  methods: {
    //获取新模板
    getTemplateList(id) {
      this.spinning = true;
      this.$httpRequest(machineRoomTemplateRendering, {
        deviceAreaId: id,
      })
        .then((res) => {
          let textKeyValue = [
            { key: 'c080e76', value: '1' },
            { key: 'g0a0g99', value: '1' },
            { key: 'f090f88', value: '1' },
            { key: 'h0b0haa', value: '71m³' },
          ];
          let infoWaterTemplateVo = {
            addEventGroupDetailForm: res.addEventGroupDetailForm,
            //base64格式图片
            bgImg: {
              base64Data: res.infoWaterTemplateVo.backgroundImg,
              type: res.infoWaterTemplateVo.backgroundImg
                ? 'normal'
                : 'default',
            },
            waterTemplateInfo: res.infoWaterTemplateVo.waterTemplateInfo,
            // keyValue: res.keyValue,
            keyValue: textKeyValue,
          };
          infoWaterTemplateVo.waterTemplateInfo.forEach((item) => {
            item.props = ['prop_data'];
            item.defaultAttr = JSON.parse(item.defaultAttr);
          });
          // 是否拥有分组逻辑
          res.addEventGroupDetailForm
            ? this.previewTemplate(infoWaterTemplateVo)
            : (this.infoWaterTemplateVo = infoWaterTemplateVo);
          this.spinning = false;
          message.success('加载成功~');
        })
        .catch(() => {
          this.spinning = false;
        });
    },
    isScreenFullEvent(val) {
      Storage.set('isScreenFull', val);
      window.parent.postMessage({ type: 'screenFull', data: val }, '*');
      this.isScreenFull = Storage.get('isScreenFull');
    },
    previewModel(id) {
      this.spinning = true;
      this.$httpRequest(infoTemplate, {
        waterTemplateId: id,
      })
        .then((res) => {
          res.data.waterTemplateInfo.forEach((item) => {
            item.defaultAttr = JSON.parse(item.defaultAttr);
          });
          this.infoWaterTemplateVo.bgImg = {
            base64Data: res.data.backgroundImg,
            type: res.data.backgroundImg ? 'normal' : 'default',
          };
          this.infoWaterTemplateVo.waterTemplateInfo =
            res.data.waterTemplateInfo;
          this.spinning = false;
          message.success('加载成功~');
        })
        .catch(() => {
          this.spinning = false;
        });
    },
    changeSelect(id) {
      this.getTemplateList(id);
      Storage.set('selectAreaId', id);
    },
    showComponentInfoModalMethod(val, e) {
      this.showComponentInfoModal = val;
      if (val) {
        let offsetX = 40;
        const componentInfoModal = this.$refs.componentInfoModal;
        componentInfoModal.style.left = e.pageX + offsetX + 'px';
        componentInfoModal.style.top = e.pageY + 'px';
      }
    },
    mouseoverSvg(e, index) {
      this.selectSvgInfo = this.infoWaterTemplateVo.waterTemplateInfo[index];
      this.showComponentInfoModalMethod(true, e);
    },
    clearSelectSvgInfo() {
      this.selectSvgInfo = {};
      this.showComponentInfoModal = false;
    },
    returnRouter() {
      this.$router.back(-1);
    },
    /**
     * 时间复杂度过大，技术有限
     * 回显模块逻辑
     * infoWaterTemplateVo 数据源 有分组情况 addEventGroupDetailForm waterTemplateInfo keyValue
     */
    previewTemplate(infoWaterTemplateVo) {
      //匹配key绑定值
      let flag = false; //分组是否关闭标识
      let TemplateArr = this.matchComponentKeyValue(infoWaterTemplateVo);
      //当前递归分情况
      let findGroupComponent = (list, flag = false) => {
        list.forEach((groupItem) => {
          //处理阀门状态
          groupItem.type == 'WaterPipeValveSvg'
            ? this.changeComponentStatus('valve', {
                groupItem,
                list: TemplateArr.waterTemplateInfo,
              })
            : '';
          //处理组件状态
          groupItem.dataKeyValue == 0 ? (flag = true) : ''; //分组（子分组）控制子分组，当其父分组为阀门关时，子分组统一关闭
          if (flag) {
            groupItem.componentsList
              ? groupItem.componentsList.forEach((groupComponentItem) => {
                  this.changeComponentStatus(
                    'component',
                    {
                      groupItem,
                      groupComponentItem,
                      list: TemplateArr.waterTemplateInfo,
                    },
                    0
                  );
                })
              : (groupItem.componentsList = []);
            groupItem.groupLists
              ? findGroupComponent(groupItem.groupLists, flag)
              : (groupItem.groupLists = []);
          } else {
            groupItem.componentsList
              ? groupItem.componentsList.forEach((groupComponentItem) => {
                  this.changeComponentStatus('component', {
                    groupItem,
                    groupComponentItem,
                    list: TemplateArr.waterTemplateInfo,
                  });
                })
              : (groupItem.componentsList = []);
            groupItem.groupLists
              ? findGroupComponent(groupItem.groupLists)
              : (groupItem.groupLists = []);
          }
        });
      };
      findGroupComponent(TemplateArr.addEventGroupDetailForm);
      this.infoWaterTemplateVo = TemplateArr;
    },
    matchComponentKeyValue(list) {
      list.waterTemplateInfo.forEach((componentItem) => {
        list.keyValue.forEach((keyItem) => {
          if (componentItem.dataKeyId == keyItem.key) {
            componentItem.dataKeyId = keyItem.key;
            componentItem.dataKeyValue = keyItem.value;
          }
          if (componentItem.stateKeyId == keyItem.key) {
            componentItem.stateKeyId = keyItem.key;
            componentItem.stateKeyValue = keyItem.value;
          }
        });
      });
      return list;
    },
    /**
     *
     * @param {*} type 类型
     * @param {*} obj 组的对象值
     * @param {*} status  当前组的状态
     */
    changeComponentStatus(type, obj, status = null) {
      //阀门状态
      let valveStatus = {
        0: '#faad14',
        1: '#00FF00',
      };
      //阀门开关
      let switchStatus = {
        0: '#FF0000',
        1: '#00FF00',
      };
      obj.list.forEach((componentItem) => {
        switch (type) {
          case 'valve':
            if (
              obj.groupItem.componentDataId == componentItem.componentDataId
            ) {
              obj.groupItem.dataKeyValue = componentItem.dataKeyValue;
              obj.groupItem.stateKeyValue = componentItem.stateKeyValue;
              //阀门状态
              componentItem.stateKeyValue
                ? (componentItem.defaultAttr.statusSwitchs.val.selectval =
                    valveStatus[componentItem.stateKeyValue])
                : '';
              //阀门开关
              componentItem.dataKeyValue
                ? (componentItem.defaultAttr.switchs.val.selectval =
                    switchStatus[componentItem.dataKeyValue])
                : '';
            }
            break;
          case 'component':
            if (
              obj.groupComponentItem.componentDataId ==
              componentItem.componentDataId
            ) {
              //JSON处理化
              obj.groupComponentItem.closeValve = JSON.parse(
                obj.groupComponentItem.closeValve
              );
              obj.groupComponentItem.openValve = JSON.parse(
                obj.groupComponentItem.openValve
              );
              obj.groupItem.stateKeyValue != null
                ? (componentItem.defaultAttr =
                    obj.groupComponentItem[
                      this.switchStatus[
                        status != null ? status : obj.groupItem.stateKeyValue
                      ]
                    ])
                : '';
              obj.groupItem.dataKeyValue != null
                ? (componentItem.defaultAttr =
                    obj.groupComponentItem[
                      this.switchStatus[
                        status != null ? status : obj.groupItem.dataKeyValue
                      ]
                    ])
                : '';
            }
            break;
        }
      });
    },
  },
};
</script>
<style scoped lang="less">
.svg-contain {
  // position: fixed;
  // left: 0;
  // right: 0;
  // top: 0;
  // bottom: 0;
}
.btns-content {
  position: fixed;
  left: 10px;
  bottom: 80px;
  button {
    margin-right: 10px;
  }
}
.cursor:hover {
  cursor: pointer;
}
.topo-layer-view-selected {
  outline: 1px solid #0cf;
}
.componentInfoModal {
  min-width: 200px;
  min-height: 100px;
  color: white;
  position: absolute;
  z-index: 99999;
  background: rgba(6, 50, 125, 0.5);
  padding: 5px;
  margin: 0px;
  display: block;
  border-radius: 5px;
  .title {
    text-align: center;
  }
}
.selectAddress {
  position: fixed;
  top: 10px;
  left: 10px;
}
.svgContent {
  height: 100%;
  width: 100%;
  background-size: cover;
  min-height: 100vh;
  -webkit-transform-origin: top left;
  transform-origin: top left;
  overflow: auto;
}

.screen {
  cursor: pointer;
  width: 100px;
  position: fixed;
  right: 10px;
  top: 10px;
  text-align: right;
  div {
    color: #1d7cd0;
    font-size: 25px;
  }
}
</style>
